package main

import (
    "context"
    "fmt"
    "net/http"
    "os"
    "strings"
    "time"
    
    "collecter/app/cache"
    "collecter/app/common/helper"
    "collecter/app/crontab"
    "collecter/app/event"
    "collecter/app/queue"
    "collecter/console"
    "collecter/route"
    
    "github.com/joho/godotenv"
)

func init() {
    if err := godotenv.Load(); err != nil {
        panic("Error loading .env file: " + err.Error())
    }
    // 系统初始化，包括 配置、日志、缓存、MySQL、redis 服务
    helper.SystemInit()
    // 缓存服务初始化
    isEnbleCache := helper.Configer.GetBool("isEnbleCache")
    if isEnbleCache {
        cache.InitCacher()
    }
    // 事件监听初始化
    event.InitEvent()
    // 定时任务初始化
    isEnableCrontab := helper.Configer.GetBool("isEnableCrontab")
    if isEnableCrontab {
        crontab.InitCrontab()
    }
    // 队列服务初始化
    isEnableQueue := helper.Configer.GetBool("isEnableQueue")
    // fmt.Printf("isEnableQueue type %T, val: %+v\n", isEnableQueue, isEnableQueue)
    if isEnableQueue {
        queue.InitQueue()
    }
    
    initRegistrar()
}

/**
 * initRegistrar
 * @Description: 初始化依赖注册器，用于避免循环引入
 */
func initRegistrar() {
    helper.EventTriggerRegister(event.Trigger)
}

func main() {
    fmt.Println("main .... ")
    testFunc()
    
    var app, cmd, name string
    // fmt.Println("main ======= ", app)
    if "console" == app {
        args := os.Args
        // fmt.Println("os.Args ======== ", os.Args)
        if len(args) > 0 {
            app = strings.Split(args[1], "=")[1]
            cmd = strings.Split(args[2], "=")[1]
            name = strings.Split(args[3], "=")[1]
        }
        // fmt.Println(app, cmd)
        
        // 命令行程序
        if err := console.Run(cmd); err != nil {
            fmt.Println(err.Error())
            os.Exit(1)
        }
        fmt.Println(cmd + " -> " + name + " execute successfully")
        os.Exit(0)
    } else {
        // http 程序
        /* 启动 web 服务器 */
        router := route.InitRouter()
        port := helper.Configer.GetString("httpport")
        srv := &http.Server{Addr: ":" + port, Handler: router}
        if err := srv.ListenAndServe(); err != nil {
            panic(err.Error())
        }
        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()
        if err := srv.Shutdown(ctx); err != nil {
            helper.Logger.Errorln("Server forced to shutdown: " + err.Error())
        }
    }
}

func testFunc() {
    /* 远程文件下载测试
       // url := "https://pgyqiniu.jiazuzhiguang.cn/chapter/2019-4-20/1555740393000770.mp4"
       // url := "https://pgyqiniu.jiazuzhiguang.cn/chapter/2019-4-3/1554271114000238.mp3"
       url := "https://pgyqiniu.jiazuzhiguang.cn/offline/2020-5-13/1589334091000148.jpg"
       // url := "https://wdoh.ucguja.cn/download/WPS%20Office_2_42337.exe"
       if err, resp := helper.Request(url, "head", nil, nil); err != nil {
       	fmt.Println("请求出错：" + err.Error())
       } else {
       	fmt.Printf("header: %+v\n", resp.Header)
       	fmt.Printf("Content-Length: %+v\n", resp.Header.Get("Content-Length"))
       	fmt.Printf("Content-Type: %+v\n", resp.Header.Get("Content-Type"))
       }
    
       t := time.Now()
       saveFile := "collects/" + t.Format(strings.Replace(time.DateOnly, "-", "/", -1))
       fullPath := enum.STATIC_DIR + saveFile
       	_, filename := path.Split(url)
       fullPath += "/" + filename
       if err := helper.DownloadRemoteFile(fullPath, url); err != nil {
       	errmsg := "写入文件内容失败。errmsg：" + err .Error()
       	fmt.Println(errmsg)
       	helper.Logger.WithField("appert", "eventerr").Error(errmsg)
       	return
       }
       fmt.Println("successfully")
       fmt.Println(fullPath)*/
}
